package com.cl.it.spider;

import com.cl.it.mbg.entity.Company;
import com.cl.it.mbg.entity.News;
import com.cl.it.utils.DateUtils;
import com.cl.it.utils.ListUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class CyzoneSpider extends AbstractSpider {

    @Override
    protected void executeSingleCompany(WebDriver driver, WebDriverWait wait, Company company) {
        driver.get("https://www.cyzone.cn/search/search/index");
        selector(driver, "input.js-search-input").sendKeys(company.getShortName());
        sleep(2000L);
        selector(driver, "a.js-search-btn-2").click();
        sleep(2000L);
        selector(driver, "span.search-tab-0").click();
        sleep(2000L);

        List<WebElement> articles = selectors(driver, "div.content-all>div.search-remm-content>div.search-remm-list-box>div.m-article-list div.item-intro");
        if (CollectionUtils.isEmpty(articles)) {
            return;
        }

        for (int i = 0; i < articles.size(); i++) {
            WebElement element = articles.get(0);
            News news = new News();
            news.setTitle(selectorText(element, "a.item-title"));
            news.setSourceUrl(selector(element, "a.item-title").getAttribute("href"));
            news.setContent(selectorText(element, "p.item-desc"));
            news.setTags(ListUtils.append(texts(selectors(element, "div.item-push-info>div.ifi-left"))));
            news.setDataSource("data_source");
            news.setSource("新闻");
            news.setNewsDate(DateUtils.dateConvert(selectorText(element, "div.item-push-info>div.ifi-right>span.time")));

            UpdateWrapper<News> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("title", news.getTitle());
            updateWrapper.eq("name", news.getName());
            newsService.saveOrUpdate(news, updateWrapper);
        }
    }

    @Override
    protected void login(WebDriver driver, WebDriverWait wait) {

    }
}
